<?php
namespace addons\sumprint\library;

use Exception;
use App\Oauth\YlyOauthClient;
use App\Api\PrintService;
use App\Config\YlyConfig;
use think\Log;
use app\admin\model\sumprint\Template as TemplateModel;

/**
 * 打印服务类
 *
 * @package addons\epay\library
 */
class Service
{
    /**
     * 提交订单
     * @param array      $param   参数
     * @param string     $template_slug   模版标识
     * @throws Exception
     */
    public static function submit($param,$template_slug,$type='yilianyun')
    {
        $addon_config = get_addon_config('sumprint');
        if($type=='yilianyun'){
            $clientId = $addon_config['yilianyun']['client_id'];//应用id
            $clientSecret = $addon_config['yilianyun']['client_secret'];//应用密钥
            $access_token = $addon_config['yilianyun']['access_token'];//调用API凭证AccessToken 永久有效,请妥善保存.
            $config = new YlyConfig($clientId, $clientSecret);
            if(!$access_token){
                $client = new YlyOauthClient($config);
                try {
                    $token = $client->getToken();
                    $access_token = $token->access_token;//调用API凭证AccessToken 永久有效,请妥善保存.
                    $addon_config['yilianyun']['access_token']=$access_token;
                    set_addon_config('sumprint',$addon_config);//写入配置文件
                } catch (Exception $e) {
                    Log::info(['ylyerror'=>$e->getMessage()]);
                    return;
                }
            }
            //获取前置配置完成
            //获取模版信息
            $sumprint_template=TemplateModel::where('slug',$template_slug)->where('type',$type)->find();
            if(!$sumprint_template||!$sumprint_template['template']){
                Log::info(['ylyerror'=>'请配置打印模版信息']);
                return;
            }
            $template=$sumprint_template['template'];
            $content=self::make_content($template,$param);
//            print_r($content);
//            exit();
            $print = new PrintService($access_token, $config);
            $origin_id=$param['origin_id'];
            $machine_code=$param['machine_code'];
            try{
                $print->index($machine_code, $content, $origin_id);
            }catch (Exception $e) {
                Log::info(['ylyerror'=>$e->getMessage()]);
                return;
            }
        }

    }
    /**
     * 替换模版中的参数
     * @param $content
     * @param $data
     * @return string
     */
    public static function make_content($content, $data) {
        if(!is_array($data)){
            return $content;
        }
        $pairs = [];
        foreach ($data as $k => $v)
        {
            $key = "{".$k."}";
            $pairs[$key] = $v;
        }
        $result = strtr($content, $pairs); // 整个数组替换
        return $result;
    }



}
